package com.ly.wxstore.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.ly.wxstore.entity.Image;
import com.ly.wxstore.entity.PrizeUserinfo;
import com.ly.wxstore.entity.UserInfo;
import com.ly.wxstore.entity.WeixinUserInfo;
import com.ly.wxstore.service.ImageService;
import com.ly.wxstore.service.PrizeUserinfoService;
import com.ly.wxstore.service.UserInfoService;
import com.ly.wxstore.service.WeixinUserInfoService;
import com.ly.wxstore.service.account.ShiroDbRealm.ShiroUser;

/**
 * 我的代理、客户查询
 * 
 * @author Peter
 */
@Controller
@RequestMapping(value = "/userInfo")
public class UserInfoController {
	
	private static Logger logger = LoggerFactory.getLogger(UserInfoController.class);

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat2, true));
	}

	@Autowired
	private ImageService imageService;
	
	@Autowired
	private WeixinUserInfoService weixinUserInfoService;
	
	@Autowired
	private PrizeUserinfoService prizeUserinfoService;
	
	@Autowired
	private UserInfoService userInfoService;
	
	//跳转到报名页面
	@RequestMapping(value = "preliminaries", method = RequestMethod.GET)
	public String preliminaries(Model model) {
		initShareHeader(model);
		return "preliminaries";
	}
	
	//跳转到报名页面
	@RequestMapping(value = "preliminaries2", method = RequestMethod.GET)
	public String preliminaries2(Model model) {
		//如果已报名，跳转到照片墙页面
		if(userInfoService.isApplied(getCurrentUser().getUid())){
			return "redirect:/userInfo/preliminaries10/desc_1";
		}
		initShareHeader(model);
		return "preliminaries2";
	}
	//跳转到报名页面
	@RequestMapping(value = "preliminaries3", method = RequestMethod.GET)
	public String preliminaries3(Model model) {
		
		initShareHeader(model);
		return "preliminaries3";
	}
	//跳转到获奖页面
	@RequestMapping(value = "preliminaries4", method = RequestMethod.GET)
	public String preliminaries4(Model model) {
		
		initShareHeader(model);
		return "preliminaries4";
	}
	
	//跳转到报名页面
	@RequestMapping(value = "preliminaries6", method = RequestMethod.GET)
	public String preliminaries6(Model model) {
		
		initShareHeader(model);
		return "preliminaries6";
	}
	
	//跳转到领奖过后的获奖页面
	@RequestMapping(value = "preliminaries11/{id}", method = RequestMethod.GET)
	public String preliminaries11(@PathVariable("id") Long id,Model model) {
		PrizeUserinfo prizeUserinfo = prizeUserinfoService.getById(id);
		
		model.addAttribute("prize", prizeUserinfo.getPrize());
		
		initShareHeader(model);
		return "preliminaries6";
	}
		
	//跳转到领奖页面
	@RequestMapping(value = "preliminaries5/{id}", method = RequestMethod.GET)
	public String preliminaries5(@PathVariable("id") Long id,Model model) {
		PrizeUserinfo prizeUserinfo = prizeUserinfoService.getById(id);
		model.addAttribute("prizeUserinfo", prizeUserinfo);
		
		initShareHeader(model);
		return "preliminaries5";
	}
	
	//保存领奖信息
	@RequestMapping(value = "preliminaries5/save", method = RequestMethod.POST)
	public String preliminaries5Save(@Valid @ModelAttribute("prizeUserinfo") PrizeUserinfo prizeUserinfo,Model model,RedirectAttributes redirectAttributes) {
		prizeUserinfo.setReceiveDate(new Date());//领取奖品日期
		prizeUserinfoService.update(prizeUserinfo);
		prizeUserinfoService.getById(prizeUserinfo.getId());
		model.addAttribute("prize", prizeUserinfoService.getById(prizeUserinfo.getId()).getPrize());
		
		initShareHeader(model);
		return "preliminaries6";
	}

	
	
	//我的奖品页面
	@RequestMapping(value = "preliminaries7", method = RequestMethod.GET)
	public String preliminaries7(Model model) {
		List<PrizeUserinfo> prizeUserinfoList = prizeUserinfoService.getByUid(getCurrentUser().getUid());
		if(prizeUserinfoList==null || prizeUserinfoList.size()==0){
			model.addAttribute("prizeSize", 0);
			initShareHeader(model);
			return "preliminaries7";
		}else{
			PrizeUserinfo prizeUserinfo = prizeUserinfoList.get(0);
			for(PrizeUserinfo p :prizeUserinfoList){
				if(p.getReasonCode().intValue()==0){
					prizeUserinfo = p;
				}
			}
			model.addAttribute("prizeSize", 1);
			model.addAttribute("prize", prizeUserinfo.getPrize());
			initShareHeader(model);
			return "preliminaries6";
		}
		
	}
	//跳转到报名页面
	@RequestMapping(value = "preliminaries8", method = RequestMethod.GET)
	public String preliminaries8(Model model) {
		
		initShareHeader(model);
		return "preliminaries8";
	}
	
	//to投票
	@RequestMapping(value = "preliminaries9/{id}", method = RequestMethod.GET)
	public String preliminaries9(@PathVariable("id") Long id,Model model) {
		
		logger.info("to投票："+id);
		
		UserInfo userInfo = userInfoService.getById(id);
		List<Image> imageList = imageService.getByUid(userInfo.getUid());
		
		model.addAttribute("userInfo", userInfo);
		model.addAttribute("imageList", imageList);
		initShareHeader(model);
		return "preliminaries9";
	}
	
	//投票
	@RequestMapping(value = "voteForFirst/{uid}", method = RequestMethod.GET)
	public String voteForFirst(@PathVariable("uid") String uid,Model model) {
		
		logger.info("投票："+uid);
		
		//判断投票条件
		//今天已为他家投票，或今天已没有票数
		String currentUid = getCurrentUser().getUid();
		
		UserInfo userInfo = userInfoService.getByUid(uid);
		model.addAttribute("userInfo", userInfo);
		//查询今天剩余的票数
		Long remainVoteNumber = userInfoService.searchRemainVote(currentUid);
		model.addAttribute("remainVoteNumber", remainVoteNumber);
		if(remainVoteNumber==0){
			//投票成功后剩余票数
			model.addAttribute("remainVoteNumber", remainVoteNumber);
			model.addAttribute("voteResult", false);
			//今天剩余的票数0
			initShareHeader(model);
			return "preliminaries4";
		}
		
		/*//查询今天已为他家投票的票数
		Long voteForHomeNumber = userInfoService.searchRemainVoteForHome(currentUid,uid);
		if(voteForHomeNumber.intValue()==1){
			//已为他家3投票
			model.addAttribute("voteForHomeNumber", voteForHomeNumber);
			return "preliminaries4";
		}*/
		
		//投票
		PrizeUserinfo prizeUserinfo = userInfoService.voteForFirst(currentUid,uid);
		if(prizeUserinfo!=null){
			//第一次投票获取奖品
			model.addAttribute("prizeUserinfo", prizeUserinfo);
		}
		//投票成功后剩余票数
		model.addAttribute("remainVoteNumber", remainVoteNumber==0?0:remainVoteNumber-1);
		model.addAttribute("voteResult", true);
		
		//是否已经领过奖品
		int received = prizeUserinfoService.getReceived(currentUid);
		model.addAttribute("received", received);
		initShareHeader(model);
		return "preliminaries4";
	}
	
	//跳转到照片墙页面
	@RequestMapping(value = "preliminaries10/{search}", method = RequestMethod.GET)
	public String preliminaries10(@PathVariable("search") String search,Model model) {
		List<UserInfo> userInfoList = userInfoService.getAll();
		
		//顺序查看 id正序
		if("desc_1".equals(search)){
			userInfoList = userInfoService.getAll();
		}
		//最新参考 id倒序
		else if("desc_2".equals(search)){
			userInfoList = userInfoService.getAllOrderByIdDesc();
			
		}
		//票数排行
		else if("desc_3".equals(search)){
			userInfoList = userInfoService.getAllOrderByFirstTicketsDesc();
		}
		model.addAttribute("condition", search);
		model.addAttribute("userInfoList", userInfoList);
		initShareHeader(model);
		return "preliminaries10";
	}
	
	// 条件查询   跳转到照片墙页面
	@RequestMapping(value = "preliminaries10", method = RequestMethod.POST)
	public String preliminaries10Search(@Valid @ModelAttribute("userInfo") UserInfo userInfo,Model model) {
		List<UserInfo> userInfoList = userInfoService.searchByNameOrId(userInfo);
		
		model.addAttribute("userInfoList", userInfoList);
		model.addAttribute("userInfo", userInfo);
		initShareHeader(model);
		return "preliminaries10";
	}
	
	// 保存
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(@Valid @ModelAttribute("userInfo") UserInfo userInfo, MultipartHttpServletRequest request, HttpServletResponse response, Model model) {
		logger.info("uploadPost called");
		Iterator<String> itr = request.getFileNames();

		//String systemId = request.getParameter("systemId");
		String phase = request.getParameter("phase");

		MultipartFile mpf;
		List<Image> list = new LinkedList<Image>();
		
		//阿里云OSS服务初始化http://huar.oss-cn-shenzhen.aliyuncs.com/QbqOaz4Dr9HZQtPXDZmEC5ZERfxtU1
		String accessKeyId = "mOjl8ioofR4CZJEP";
		String accessKeySecret = "QbqOaz4Dr9HZQtPXDZmEC5ZERfxtU1";
		String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
		
		
		int i = 0;
		while (itr.hasNext()) {
			
			mpf = request.getFile(itr.next());
			
			if(StringUtils.isBlank(mpf.getOriginalFilename())){
				break;
			}
			try {
				String newFilenameBase = UUID.randomUUID().toString();
				String originalFileExtension = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
				String newFilename = newFilenameBase + originalFileExtension;
				logger.info("Uploading {}({})", mpf.getOriginalFilename(),newFilename);
				ObjectMetadata meta = new ObjectMetadata();
			    // 必须设置ContentLength
			    meta.setContentLength(mpf.getSize());
			    
			    // 上传Object.
			    OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
			    PutObjectResult result = client.putObject("huar", "city-represent/"+newFilename, mpf.getInputStream(), meta);

			    
			    // 打印ETag
			    logger.info("newFilename uploading to OSS result:"+result.getETag());
		    
		
				Image image = new Image();
				image.setName(mpf.getOriginalFilename());
				image.setSize(mpf.getSize());
				//image.setThumbnailFilename(thumbnailFilename);
				//image.setThumbnailSize(thumbnailFile.length());
				
				image.setNewFilename(newFilename);//大图
				image.setContentType( mpf.getContentType());
				image.setCreateDate(new Date());
				image.setUpdateDate(new Date());
				image.setCreateUser(1L);
				image.setPhase(phase);
				image.setUuid(newFilenameBase);
				image.setUid(getCurrentUser().getUid());
				imageService.save(image);

				image.setUrl(image.getNewFilename());
				//image.setThumbnailUrl(image.getThumbnailFilename());
				//image.setDeleteUrl("/my/image/delete/" + image.getUuid());
				//image.setDeleteType("DELETE");

				list.add(image);
				
				//设置主图片
				i++;
				if(i==1){
					userInfo.setMainImageUrl(image.getNewFilename());
				}
				logger.info("Uploading {}", image);

			} catch (Exception e) {
				logger.error("Could not upload file " + mpf.getOriginalFilename(), e);
			}
		}

		Map<String, Object> files = new HashMap<String, Object>();
		files.put("files", list);
		
		userInfo.setUid(getCurrentUser().getUid());
		userInfo.setCreateDate(new Date());
		userInfo.setFirstTickets(0L);
		userInfo.setSecondTickets(0L);
		userInfo.setLevel(1L);
		PrizeUserinfo prizeUserinfo = userInfoService.save(userInfo);
		model.addAttribute("prizeUserinfo", prizeUserinfo);
		
		//是否已经领过奖品
		int received = prizeUserinfoService.getReceived(getCurrentUser().getUid());
		model.addAttribute("received", received);
		initShareHeader(model);
		return "preliminaries11";
	}
	
	/*// 保存
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(@Valid @ModelAttribute("userInfo") UserInfo userInfo, MultipartHttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		logger.info("uploadPost called");
		Iterator<String> itr = request.getFileNames();

		//String systemId = request.getParameter("systemId");
		String phase = request.getParameter("phase");

		MultipartFile mpf;
		List<Image> list = new LinkedList<Image>();
		int i = 0;
		while (itr.hasNext()) {
			mpf = request.getFile(itr.next());
			logger.info("Uploading {}", mpf.getOriginalFilename());
			if(StringUtils.isBlank(mpf.getOriginalFilename())){
				break;
			}

			String newFilenameBase = UUID.randomUUID().toString();
			String originalFileExtension = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
			String newFilename = newFilenameBase + originalFileExtension;
			// String storageDirectory = fileUploadDirectory;
			String storageDirectory = ServerPathUtils.getImageDir(request);// 绝对路径

			String contentType = mpf.getContentType();

			File newFile = new File(storageDirectory + File.separator + newFilename);
			try {
				
				
				mpf.transferTo(newFile);
				
				//大图
				BufferedImage thumbnailBig = Scalr.resize(ImageIO.read(newFile), Scalr.Method.SPEED, Scalr.Mode.FIT_TO_WIDTH, 600, 600, Scalr.OP_ANTIALIAS);// 生成缩略图
				String thumbnailFilenameBig = newFilenameBase + "-big.png";
				File thumbnailFileBig = new File(storageDirectory + File.separator + thumbnailFilenameBig);
				ImageIO.write(thumbnailBig, "png", thumbnailFileBig);

				//小图
				BufferedImage thumbnail = Scalr.resize(ImageIO.read(newFile), Scalr.Method.SPEED, Scalr.Mode.FIT_TO_WIDTH, 100, 100, Scalr.OP_ANTIALIAS);// 生成缩略图
				String thumbnailFilename = newFilenameBase + "-thumbnail.png";
				File thumbnailFile = new File(storageDirectory + File.separator + thumbnailFilename);
				ImageIO.write(thumbnail, "png", thumbnailFile);

				Image image = new Image();
				image.setName(mpf.getOriginalFilename());
				image.setSize(mpf.getSize());
				image.setThumbnailFilename(thumbnailFilename);
				image.setThumbnailSize(thumbnailFile.length());
				
				image.setNewFilename(thumbnailFilenameBig);//大图
				image.setContentType(contentType);
				image.setCreateDate(new Date());
				image.setUpdateDate(new Date());
				image.setCreateUser(1L);
				image.setPhase(phase);
				image.setUuid(newFilenameBase);
				image.setUid(getCurrentUser().getUid());

				imageService.save(image);

				image.setUrl(image.getNewFilename());
				image.setThumbnailUrl(image.getThumbnailFilename());
				image.setDeleteUrl("/my/image/delete/" + image.getUuid());
				image.setDeleteType("DELETE");
				

				list.add(image);
				
				//设置主图片
				i++;
				if(i==1){
					userInfo.setMainImageUrl(image.getThumbnailFilename());
				}
				logger.info("Uploading {}", image);

			} catch (IOException e) {
				logger.error("Could not upload file " + mpf.getOriginalFilename(), e);
			}

			
		}

		Map<String, Object> files = new HashMap<String, Object>();
		files.put("files", list);
		
		userInfo.setUid(getCurrentUser().getUid());
		userInfo.setCreateDate(new Date());
		userInfo.setFirstTickets(0L);
		userInfo.setSecondTickets(0L);
		userInfo.setLevel(1L);
		userInfoService.save(userInfo);
		redirectAttributes.addFlashAttribute("message", "操作成功");
		return "redirect:/userInfo/preliminaries3";
	}*/
	
	// 跳转到上传家庭图片页面
	@RequestMapping(value = "toFamilyUploadPhoto", method = RequestMethod.GET)
	public String toFamilyUploadPhoto(Model model) {
		initShareHeader(model);
		return "family-upload-photos";
	}
	
	// 删除
	@RequestMapping(value = "delete/{id}")
	public String delete(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
		userInfoService.delete(id);
		redirectAttributes.addFlashAttribute("message", "删除成功");
		return "redirect:/userInfo/list";
	}
	
	//模拟朋友圈
	@RequestMapping(value = "timeline", method = RequestMethod.GET)
	public String timeline(Model model) {
		initShareHeader(model);
		return "timeline";
	}
	
	private void initShareHeader(Model model) {
		ShiroUser user = getCurrentUser();
    	String openId = user.getOpenid();
    	if(StringUtils.isBlank(user.getImageHeaderUrl())){
    		WeixinUserInfo weixinUserInfo = weixinUserInfoService.receiveWeixinUserInfoByOpenId(openId);
    		user.setImageHeaderUrl(weixinUserInfo.getHeadimgurl());
    		user.setNickName(weixinUserInfo.getNicknameForBase64Decoder());
    	}
    	
    	model.addAttribute("headimgurl", user.getImageHeaderUrl());
		model.addAttribute("nickName", user.getNickName());
			
	}
	
	public ShiroUser getCurrentUser() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user;
	}
	
}
